package com.uto;

import java.util.Map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

import com.uto.backend.AppService;
import com.uto.backend.interfaces.IAppManager;
import com.uto.backend.interfaces.IServerResponse;
import com.uto.frontend.interfaces.IServiceListener;

public class UTO extends Activity implements Runnable{

	public static final String HTTP_THREAD = "HTTP_THREAD";

	public final static String USER_FILE = "uto_user_status";
	
	private final String TAG = "com.uto.UTO";

	private final int USER_IN_GAME = 0;
	private final int USER_SINGED_IN = 1;
	private final int USER_NEW = 2;

	//A progress dialog for when waiting for background work
	private ProgressDialog pd;

	//The user currently singed in
	private User user;

	//A thread to do some background work
	private Thread thread;
	
	private final int IS_OK = 0;
	private final int NOT_OK = 1;


	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
	}

	@Override
	protected void onStart() {
		super.onStart();

		//try starting the background service
		Intent mainIntent = new Intent(new Intent(getApplicationContext() , AppService.class));
		boolean bind = true;
		if (MyServiceConnection.getAppManager()==null)
		{
			bind = bindService(mainIntent, new MyServiceConnection() , Context.BIND_AUTO_CREATE);
		}
		if (bind){			
			//show a progress dialog while reading saved data from the disk
			pd = ProgressDialog.show(this, getString(R.string.loading) , "", true, false);
			thread = new Thread(this);
			thread.start();
		}

		else{
			Toast.makeText(this, "could not bind to service", Toast.LENGTH_LONG).show();
		}
	}

	@Override
	protected void onStop(){
		if (pd!=null && pd.isShowing())
			pd.dismiss();

		if (thread!=null && thread.isAlive())
			thread.stop();

		super.onStop();

	}

	private void setStatus(int userStatus){
		pd.dismiss();
		switch (userStatus){
		case USER_NEW:
			//Start an activity for the user to register to the game
			startActivity(new Intent(this , Register.class));
			break;

		case USER_SINGED_IN:
			//Start an activity for the user to choose a game to play
			Intent intent = new Intent(this , GameChooser.class);
			intent.putExtra("user", user);
			startActivity(intent);

			break;

		case USER_IN_GAME:

			//show a new progress dialog while getting game proprties from the server
			try {
				IAppManager manager = MyServiceConnection.getAppManager();
				if (manager!=null)
//					manager.login(user, listener);
					manager.updateGameData(user.getUsername(), listener);
			} catch (RemoteException e) {
				e.printStackTrace();
				break;
			}
			pd = ProgressDialog.show(this, getString(R.string.welcome_header)+ user.getFirstName() + " " + user.getLastName(),
					getString(R.string.welcome_body));
		}
		finish();


	}

	public void run() {
		// check in DB if user is singed in
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int userStatus = getUserStatus();
		statusHandler.sendEmptyMessage(userStatus);
	}

	private int getUserStatus() {
		// Restore preferences
		SharedPreferences settings = getSharedPreferences(USER_FILE, 0);
		if (settings==null)
			return USER_NEW;

		String username = settings.getString("username", null);
		String password = settings.getString("password", null);
		if (username==null || password==null)
			return USER_NEW;

		String firstName = settings.getString("firstName", null);
		String lastName = settings.getString("lastName", null);
		int money = settings.getInt("money", 0);
		String streets = settings.getString("streets", null);
		user = new User(username , password ,firstName , lastName, money, streets);

		boolean inGame = settings.getBoolean("inGame", false);
		if (inGame)
			return USER_IN_GAME;
		else
			return USER_SINGED_IN;
	}

	private Handler statusHandler = new Handler(){
		public void handleMessage(Message msg){
			setStatus(msg.what);

		}
	};
	
	private Handler loginHandler = new Handler(){
		public void handleMessage(Message msg){
			if (pd!=null && pd.isShowing())
				pd.dismiss();

			if (msg.arg1==NOT_OK){
				String message = (String)msg.obj;
				if (message != null)
					Toast.makeText(UTO.this, message, Toast.LENGTH_LONG).show();
				else
					Toast.makeText(UTO.this, getString(R.string.login_fail), Toast.LENGTH_LONG).show();
			}
			else{
				Intent gameIntent = new Intent(UTO.this, MapViewOpenStreet.class);
				gameIntent.putExtra("user" , user);
				startActivity(gameIntent);
				
			}



		}
	};

	private final IServiceListener.Stub listener = new IServiceListener.Stub(){

		public void handleMessage(IServerResponse response) {
			Message msg = new Message();
			try {
				if (response == null)
				{
					msg.arg1 = NOT_OK;
					loginHandler.sendMessage(msg);
					Log.e(TAG, "null response");
				}

				else if (!response.isOk())
				{
					msg.arg1 = NOT_OK;
					msg.obj = response.getMessage();
					loginHandler.sendMessage(msg);
				}
				else{
					msg.arg1 = IS_OK;
					user = (User)response.getData().get("curUser");
					loginHandler.sendMessage(msg);					
				}
			} catch (Exception e) {
				msg.arg1 = NOT_OK;
				loginHandler.sendMessage(msg);
				e.printStackTrace();
			}
		}
	};



}